﻿using System;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WalkingTec.Mvvm.Core;
using WalkingTec.Mvvm.Core.Extensions;
using WalkingTec.Mvvm.Mvc;
using WalkingTec.Mvvm.Mvc.Admin.ViewModels.FrameworkUserVms;
using SAASDEMO.ViewModel.HomeVMs;
using Microsoft.AspNetCore.Http;
using System.Text;
using SAASDEMO.DataAccess;
using SAASDEMO.Model;
using System.Linq;

namespace SAASDEMO.Controllers
{
    [AllRights]
    public class LoginController : BaseController
    {
        #region 获取当前url
        public string GetAbsoluteUri(HttpRequest request)
        {
            return new StringBuilder()
                .Append(request.Scheme)
                .Append("://")
                .Append(request.Host)
                .Append(request.PathBase)
                .Append(request.Path)
                .Append(request.QueryString)
                .ToString();
        }
        #endregion

        [Public]
        [ActionDescription("Login")]
        public IActionResult Login()
        {
            LoginVM vm = Wtm.CreateVM<LoginVM>();
            string TenantKey = "default";
            string displayUrl = GetAbsoluteUri(HttpContext.Request);
            displayUrl = displayUrl.Replace("http://", "").Replace("https://", "") + "/";
            displayUrl = displayUrl.Substring(0, displayUrl.IndexOf("/"));
            var ZDC = new DataContext(Wtm.ConfigInfo.Connections[0].Value, DBTypeEnum.SqlServer);
            var Tenant = ZDC.Set<Tenant>().Where(x => x.DomainName.Replace("http://", "").Replace("https://", "") == displayUrl).FirstOrDefault();
            if (Tenant != null)
            {
                TenantKey = "SAASDEMODB" + Tenant.Code;
                Wtm.Session.Set("TenantKey", "SAASDEMODB" + Tenant.Code);
            }
            else
            {
                Wtm.Session.Set("TenantKey", TenantKey);
            }
            int i = 0;
            foreach (var item in Wtm.ConfigInfo.Connections)
            {
                if (item.Key == TenantKey)
                {
                    i++;
                    break;
                }
            }
            if (i == 0)
            {
                CS cs = new CS();
                cs.DbContext = "DataContext";
                cs.DbType = DBTypeEnum.SqlServer;
                cs.Key = TenantKey;
                cs.Value = Wtm.ConfigInfo.Connections[0].Value.Replace("SAASDEMODB", cs.Key);
                cs.DcConstructor = Wtm.ConfigInfo.Connections[0].DcConstructor;
                Wtm.ConfigInfo.Connections.Add(cs);
            }
            vm.Redirect = HttpContext.Request.Query["ReturnUrl"];
            if (Wtm.ConfigInfo.IsQuickDebug == true)
            {
                vm.ITCode = "admin";
                vm.Password = "000000";
            }
            return View(vm);
        }

        [Public]
        [HttpPost]
        public async Task<ActionResult> Login(LoginVM vm)
        {
            if (Wtm.ConfigInfo.IsQuickDebug == false)
            {
                var verifyCode = HttpContext.Session.Get<string>("verify_code");
                if (string.IsNullOrEmpty(verifyCode) || verifyCode.ToLower() != vm.VerifyCode.ToLower())
                {
                    vm.MSD.AddModelError("", Localizer["Login.ValidationFail"]);
                    return View(vm);
                }
            }

            var user = await vm.DoLoginAsync();
            if (user == null)
            {
                return View(vm);
            }
            else
            {
                Wtm.LoginUserInfo = user;
                string url = string.Empty;
                if (!string.IsNullOrEmpty(vm.Redirect))
                {
                    url = vm.Redirect;
                }
                else
                {
                    url = "/";
                }

                AuthenticationProperties properties = null;
                if (vm.RememberLogin)
                {
                    properties = new AuthenticationProperties
                    {
                        IsPersistent = true,
                        ExpiresUtc = DateTimeOffset.UtcNow.Add(TimeSpan.FromDays(30))
                    };
                }

                var principal = user.CreatePrincipal();
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, properties);
                return Redirect(HttpUtility.UrlDecode(url));
            }
        }

        [Public]
        public IActionResult Reg()
        {
            var vm = Wtm.CreateVM<RegVM>();
            return PartialView(vm);
        }

        [Public]
        [HttpPost]
        public IActionResult Reg(RegVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                var rv = vm.DoReg();
                if (rv == true)
                {
                    return FFResult().CloseDialog().Message(Localizer["Reg.Success"]);
                }
                else
                {
                    return PartialView(vm);
                }
            }
        }

        [AllRights]
        [ActionDescription("Logout")]
        public async Task Logout()
        {
            await Wtm.RemoveUserCache(Wtm.LoginUserInfo.ITCode);
            HttpContext.Session.Clear();
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.Response.Redirect("/");
        }

        [AllRights]
        [ActionDescription("ChangePassword")]
        public ActionResult ChangePassword()
        {
            var vm = Wtm.CreateVM<ChangePasswordVM>();
            vm.ITCode = Wtm.LoginUserInfo.ITCode;
            return PartialView(vm);
        }

        [AllRights]
        [HttpPost]
        [ActionDescription("ChangePassword")]
        public ActionResult ChangePassword(ChangePasswordVM vm)
        {
            if (!ModelState.IsValid)
            {
                return PartialView(vm);
            }
            else
            {
                vm.DoChange();
                return FFResult().CloseDialog().Alert(Localizer["Login.ChangePasswordSuccess"]);
            }
        }

    }
}
